package com.baymax.test.scene;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentContainer;
import androidx.fragment.app.FragmentManager;

import java.io.PrintWriter;
import java.lang.reflect.Field;

public class Hook {
    private static Field hookedContainerField;

    public static void hookFragmentContainer(FragmentManager childFragmentManager) {
        try {
            if (hookedContainerField == null) {
                Class<?> fmClaz = childFragmentManager.getClass().getSuperclass();
                if (fmClaz == null) {
                    return;
                }
                Field ff = fmClaz.getDeclaredField("mContainer");
                ff.setAccessible(true);
                hookedContainerField = ff;
            }
            Field containerFF = hookedContainerField;
            FragmentContainer o = (FragmentContainer) containerFF.get(childFragmentManager);
            if (o != null) {
                MultiFlowContainer hookContainer = new MultiFlowContainer(o );
                containerFF.set(childFragmentManager, hookContainer);
                try (PrintWriter writer = new PrintWriter(System.out);) {
                    childFragmentManager.dump("hook-->" , null , writer ,null);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    static class MultiFlowContainer extends FragmentContainer {
        private final FragmentContainer realContainer;

        MultiFlowContainer(FragmentContainer realContainer) {
            this.realContainer = realContainer;
        }


        @Override
        public View onFindViewById(int id) {
            return  realContainer.onFindViewById(id);
        }

        @Override
        public boolean onHasView() {
            return realContainer.onHasView();
        }

        @Override
        public Fragment instantiate(Context context, String className, Bundle arguments) {
            System.out.println(className);
            return super.instantiate(context, className, arguments);
        }
    }
}
